<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use app\api\model\goods\Goods as GoodsModel;

/**
 * 三方报告接口
 */
class TripartiteReport extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $account = 'baijiajiance';
    protected $password = '310b4f8b3095b08d6b1cff65a09cd583';

    protected $beforeActionList = ['checkLogin'];

    public function checkLogin()
    {
        // parent::_initialize();
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if(!$account || !$password){
            $this->error('请输入账号密码');
        }
        if($account != $this->account || $password != $this->password){
            $this->error('账号密码错误');
        }
        $data = $this->request->input();
        \think\Log::record('三方报告接口入参,方法名：'.$this->request->action());
        \think\Log::record(json_encode($data));
    }


    /** 获取订单列表 */
    public function getOrderList(){
        $page = $this->request->post('page', 1);
        $limit = $this->request->post('limit', 10);
        $between = $this->request->post('between/a', null);
        if(!$between || count($between) != 2){
            $between = [date('Y-m-d 00:00:00'),date('Y-m-d 23:59:59')];
        }
        $between[0] = strtotime($between[0]);
        $between[1] = strtotime($between[1]);
        $list = \app\api\model\order\OrderMaster::where('status',30)->where('songjiantime','between',$between)->where('report_status',10)->with(['ordergoods','hospital2','orderTube','doctor'])->paginate($limit, false, ['page' => $page]);
        $this->success('',$list);
    }

    /** 开始检测 */
    public function startOrderReport(){
        $orderId = $this->request->post('order_id/a',null);

        if(!$orderId || count($orderId) == 0){
            $this->error('参数错误');
        }
        Db::startTrans();
        try{ 
            foreach ($orderId as $key => $value) {
                $order = \app\api\model\order\OrderMaster::get($value);
                if(!$order){
                    throw new \Exception("ID:{$value},订单不存在");
                }
                if($order->status != 30 ){
                    throw new \Exception("ID:{$value},订单状态错误");
                }
                if($order->report_status != 10){
                    throw new \Exception("ID:{$value},报告状态错误");
                }
                
                $order->report_status = 20;
                $order->save();
            }
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        Db::commit();
        $this->success('开始检测成功');

    }


    /** 完成订单 */
    public function completeOrderReport(){
        $orderId = $this->request->post('order_id/a',null);

        if(!$orderId || count($orderId) == 0){
            $this->error('参数错误');
        }
        
        Db::startTrans();
        try{ 

            foreach ($orderId as $key => $value) {
                $order = \app\api\model\order\OrderMaster::get($value);
                if(!$order){
                    throw new \Exception("ID:{$value},订单不存在");
                }
                if($order->status != 30 ){
                    throw new \Exception("ID:{$value},订单状态错误");
                }
                if($order->report_status == 30){
                    throw new \Exception("ID:{$value},订单已完成，请勿重复操作");
                }
            
                $order->report_status = 30;
                $order->overtime = time();
                $res = $order->save();
                if(!$res){
                    throw new \Exception('订单完成失败');
                }

                // 佣金
                $price = 0;
                $saleInfo = \app\api\model\User::where('id',$order->sole_id)->find();
                $common_discount = $saleInfo->discount;

                $between = [date('Y-m-01 00:00:00', strtotime('last month')),date('Y-m-t 23:59:59', strtotime('last month'))];
                $saleRank = \app\api\model\SaleRank::where('user_id',$order->sole_id)->where('date','between',$between)->find();
                if($saleRank && $saleRank->discount > 0){
                    $common_discount = $saleRank->discount;
                }
                if($common_discount < 0){
                    $common_discount = 0;
                }
                if($common_discount > 100){
                    $common_discount = 100;
                }

                $discount = $common_discount / 100;
                $orderGoods = \app\api\model\order\OrderGoods::where('order_master_id',$order->id)->select();
                foreach ($orderGoods as $key => $value) { 
                    $sale_discount = Db::name('sale_discount')->where('goods_id',$value->goods_id)->where('sale_id',$order->sole_id)->find();
                    if($sale_discount){
                        $price = $price + $value->real_price - $sale_discount['money'];
                    }else{
                        $price = $price + $value->real_price - $value->price * $discount;
                    }
                }



                $commissionRecords = new \app\api\model\CommissionRecords();
                $res = $commissionRecords->save([
                    'sale_id'=>$order->sole_id,
                    'hospital_id'=>$order->hospital_id,
                    'commission_discount'=>$common_discount,
                    'commission_price'=>round($price < 0.01 ? 0.01 : $price,2),
                    'order_id'=>$order->id,
                    'out_trade_no'=>$order->out_trade_no
                ]);
                if(!$res){
                    throw new \Exception('订单完成失败');
                }

                $user = \app\api\model\User::find($order->sole_id);
                $user->setUpdateMoneyParams([
                    'memo'=>'订单完成分佣',
                    'title'=>'订单完成分佣',
                    'datatype'=>20
                ]);
                $user->money = $user->money + round($price < 0.01 ? 0.01 : $price,2);
                $res = $user->save();
                if(!$res){
                    throw new \Exception('订单完成失败');
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('订单完成成功');

    }

    /** 生成报告 */
    public function createReport(){
        $orderId = $this->request->post('order_id');
        $report_image = $this->request->post('report_image');
        $report_content = $this->request->post('report_content');
        $tripartite_report_id = $this->request->post('tripartite_report_id');

        if(!$orderId || !$report_image || !$report_content || !$tripartite_report_id){
            $this->error('参数错误');
        }
        $order = \app\api\model\order\OrderMaster::get($orderId);
        if(!$order){
            $this->error('订单不存在');
        }
        if($order->status != 30 ){
            $this->error('订单状态错误');
        }

        if($order->report_status != 30){
            $order->report_status = 25;
            $order->save();
        }
        
        $model = \app\api\model\order\OrderReport::where('tripartite_report_id',$tripartite_report_id)->where('order_id',$orderId)->find();
        if($model){
            $model->report_image = $report_image;
            $model->report_content = $report_content;
            $model->downloadstatus = 10;
            $model->createtime = time();
            $model->save();

            if($order->download_report_status == 30){
                $order->download_report_status = 20;
                $order->save();
            }
            $this->success('操作成功');
        }else{
            $orderReport = new \app\api\model\order\OrderReport();
            $orderReport->order_id = $orderId;
            $orderReport->report_image = $report_image;
            $orderReport->report_content = $report_content;
            $orderReport->tripartite_report_id = $tripartite_report_id;
            $orderReport->save();
            $this->success('操作成功');
        }

    }


     /**
     * 获取项目列表
     */
    public function lists(){
        $page = $this->request->post('page',1);
        $limit = $this->request->post('limit',10);
        $type = $this->request->post('type',10);
        $where = [];

        if ($this->request->get('title')){
            $where['title'] = ['like','%'.$this->request->get('title').'%'];
        }
        // if ($this->request->get('goods_category_id')){
        //     $where['goods_category_id'] = $this->request->get('goods_category_id');
        // }
        $where['pushtime'] = ['<>',Db::raw('updatetime')];
        $where['type'] = ['=',$type];
        $data = GoodsModel::where($where)->paginate($limit, false, ['page' => $page]);

        foreach($data as $v){
            // Db::name('goods')->where(['id'=>$v->id])->update(['pushtime'=>$v->updatetime]);
        }
        $this->success('',$data);
    }

    /**
     * 获取项目类型
     */
    public function category(){
        $list = (new \app\api\model\goods\GoodsCategory())->select();
        $this->success('',$list);
    }

    /**
     * 获取标本类型
     */
    public function biaobentype(){
        $list = (new \app\api\model\goods\BiaobenType())->select();
        $this->success('',$list);
    }

    /**
     * 获取容器
     */
    public function rongqi(){
        $list = (new \app\api\model\goods\BiaobenRongqi())->select();
        $this->success('',$list);
    }

    /**
     * 套餐列表
     */
    public function package(){
        $page = $this->request->get('page',1);
        $limit = $this->request->get('limit',10);
        $where = [];
        $data = (new \app\api\model\goods\GoodsPackage())->where($where)->paginate($limit, false, ['page' => $page]);
        $this->success('',$data);
    }

    public function goodsCorrelation(){
        $goods_no = $this->request->post('goods_no');
        if(!$goods_no){
            $this->error('参数错误');
        }
        $model = (new \app\api\model\goods\Goods())->where('goods_no','=',$goods_no)->find();
        if(!$model){
            $this->error('检测项目不存在');
        }
        $data = (new \app\api\model\goods\GoodsDetails())->alias('goods_detail')->field('goods.goods_no,goods_detail.*')->join('goods','goods.id = goods_detail.goods_id')->where(['goods_master_id'=>$model->id])->select();
        foreach ($data as $key => $value) {
            $data[$key]['goods_no_master'] = $goods_no;
        }
        $this->success('',$data); 

    }



}